package ren.nearby.main;

import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.orhanobut.logger.Logger;

import net.bither.util.NativeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

import io.github.tonnyl.light.Light;
import ren.nearby.lib.ui.base.BaseActivity;

/**
 * Created by Administrator on 2018/4/25 0025.
 */

public class CompressAct extends BaseActivity {

    static final int REQUEST_ALBUM = 0;
    TextView main_tv_before_after;
    ImageView main_compress_before;
    ImageView main_compress_after;
    Button btn_compress;
    Button btn_choose;
    File saveFile;
    Bitmap bitmap;
    RadioGroup main_compress_rg;
    StringBuffer sb = new StringBuffer();


    @Override
    public int getLayoutRes() {
        return R.layout.main_compress;
    }

    @Override
    public void initView() {
        super.initView();

        toolBarBuilder
                .setIconLeft(R.mipmap.btn_back_white)
                .setBack(true)
                .setTitle(getResources().getString(R.string.main_compress))
                .setBackgroundColor(R.color.text_menu_pink)
                .setTitleColor(R.color.white)
                .build();
        //android/data/项目目录/cache/
        saveFile = new File(getActivity().getExternalCacheDir() + "", "compress_" + System.currentTimeMillis() + ".jpg");
        main_tv_before_after = findViewById(R.id.main_tv_before_after);
        main_compress_before = findViewById(R.id.main_compress_before);
        main_compress_after = findViewById(R.id.main_compress_after);
        btn_compress = findViewById(R.id.btn_compress);
        btn_choose = findViewById(R.id.btn_choose);
        main_compress_rg = findViewById(R.id.main_compress_rg);
        btn_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/jepg");
                startActivityForResult(intent, CompressAct.CONTEXT_INCLUDE_CODE);
            }
        });
        btn_compress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int quality = 720;
                if (bitmap != null) {
                    for (int i = 0; i < main_compress_rg.getChildCount(); i++) {
                        RadioButton rb = (RadioButton) main_compress_rg.getChildAt(i);
                        if (rb.isChecked()) {
                            switch (Integer.valueOf(rb.getText().toString().trim())) {
                                case NativeUtil.QUALITY_320P:
                                    quality = 320;
                                    break;
                                case NativeUtil.QUALITY_360P:
                                    quality = 360;
                                    break;
                                case NativeUtil.QUALITY_480P:
                                    quality = 480;
                                    break;
                                case NativeUtil.QUALITY_720P:
                                    quality = 720;
                                    break;
                                case NativeUtil.QUALITY_1080P:
                                    quality = 1080;
                                    break;
                                case NativeUtil.QUALITY_2K:
                                    quality = 1440;
                                    break;
                                case NativeUtil.QUALITY_4K:
                                    quality = 2160;
                                    break;
                            }
                        }
                    }
                    Logger.e("===compressImage===", "====开始==压缩==saveFile==" + saveFile.getAbsolutePath());
                    NativeUtil.compressBitmap(bitmap, saveFile.getAbsolutePath(), quality);
                    Logger.e("===compressImage===", "====完成==压缩==saveFile==" + saveFile.getAbsolutePath());
                    Logger.e(bitmap == null ? "1" : "0");
                    Bitmap bm = BitmapFactory.decodeFile(saveFile.getAbsolutePath());
                    main_compress_after.setImageBitmap(bm);
                    after = fileSize(saveFile);
                    Light.info(btn_choose, "压缩完毕", Light.LENGTH_SHORT).show();
                    Logger.e(before + " - " + after);
                    sb.append("before size：" + FormetFileSize(before) + " / after size：" + FormetFileSize(after) + "\n");
                    main_tv_before_after.setText(sb.toString());
                } else {
                    Light.error(btn_choose, "bitmap null", Light.LENGTH_SHORT).show();
                }
            }
        });
    }

    private String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");

        String fileSizeString = "";

        String wrongSize = "0B";

        if (fileS == 0) {

            return wrongSize;

        }

        if (fileS < 1024) {

            fileSizeString = df.format((double) fileS) + "B";

        } else if (fileS < 1048576) {

            fileSizeString = df.format((double) fileS / 1024) + "KB";

        } else if (fileS < 1073741824) {

            fileSizeString = df.format((double) fileS / 1048576) + "MB";

        } else {

            fileSizeString = df.format((double) fileS / 1073741824) + "GB";

        }

        return fileSizeString;

    }


    public long fileSize(File file) {
        if (file == null) {
            return 0;
        }
        long size = 0;
        if (file.exists()) {
            try {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return size;
    }

    long before;
    long after;

    public File getFileByUri(Uri uri) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
            Logger.e("Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.e("requestCode = " + requestCode + " : resultCode = " + requestCode + " : data = " + data);
        try {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
                main_compress_before.setImageBitmap(bitmap);
                File file = getFileByUri(imageUri);

                before = fileSize(file);
                Logger.e(" file " + file.getAbsoluteFile() + " / before = " + before);
            } else {
                Light.error(btn_choose, " Uri null", Light.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static String getRealPathFromUri_Api11To18(Context context, Uri uri) {
        String filePath = null;
        String[] projection = {MediaStore.Images.Media.DATA};

        CursorLoader loader = new CursorLoader(context, uri, projection, null,
                null, null);
        Cursor cursor = loader.loadInBackground();

        if (cursor != null) {
            cursor.moveToFirst();
            filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
            cursor.close();
        }
        return filePath;
    }
}
